#pragma once
#include "cocos2d.h"
#include "Box2D/Box2D.h"
#include "Box2d/Dynamics/b2WorldCallbacks.h"
#include "CBullet.h"
USING_NS_CC;

class ContactPoint : public CCObject
{
public:
	b2Fixture* m_pB2FixtureA;
	b2Fixture* m_pB2FixtureB;
};

static CCArray gContactPoints;
static int32 gContactPointNum = 0;

class CCb2ContactListener : public b2ContactListener
{
public:
	CCb2ContactListener(void){};
	~CCb2ContactListener(void){};
	void BeginContact(b2Contact* contact) 
	{
		CCLog("CCb2ContactListener::BeginContact");
		//B2_NOT_USED(contact);
		b2Fixture* pFixtureA = contact->GetFixtureA();
		b2Fixture* pFixtureB = contact->GetFixtureB();
		ContactPoint *pCP = new ContactPoint;
		pCP->m_pB2FixtureA = pFixtureA;
		pCP->m_pB2FixtureB = pFixtureB;
		gContactPoints.addObject(pCP);
		gContactPointNum = gContactPoints.count();
	}

	/// Called when two fixtures cease to touch.
	void EndContact(b2Contact* contact)
	{ 
		CCLog("CCb2ContactListener::EndContact");
		//B2_NOT_USED(contact);
	}

	/// This is called after a contact is updated. This allows you to inspect a
	/// contact before it goes to the solver. If you are careful, you can modify the
	/// contact manifold (e.g. disable contact).
	/// A copy of the old manifold is provided so that you can detect changes.
	/// Note: this is called only for awake bodies.
	/// Note: this is called even when the number of contact points is zero.
	/// Note: this is not called for sensors.
	/// Note: if you set the number of contact points to zero, you will not
	/// get an EndContact callback. However, you may get a BeginContact callback
	/// the next step.
	void PreSolve(b2Contact* contact, const b2Manifold* oldManifold)
	{
		CCLog("CCb2ContactListener::PreSolve");
		const b2Manifold* manifold = contact->GetManifold();
		if(manifold->pointCount==0)
			return;
		b2Fixture* pFixtureA = contact->GetFixtureA();
		b2Fixture* pFixtureB = contact->GetFixtureB();
		//CCBullet* pBulletA = (CCBullet* )pFixtureA->GetBody()->GetUserData();
		//pBulletA->m_bIsLive = false;
		//CCBullet* pBulletB = (CCBullet* )pFixtureB->GetBody()->GetUserData();
		//pBulletB->m_bIsLive = false;

		for(int32 i=0;i < manifold->pointCount; ++i)
		{
			ContactPoint *pCP = new ContactPoint;
			pCP->m_pB2FixtureA = pFixtureA;
			pCP->m_pB2FixtureB = pFixtureB;
			gContactPoints.addObject(pCP);
			gContactPointNum = gContactPoints.count();
		}
	}

	/// This lets you inspect a contact after the solver is finished. This is useful
	/// for inspecting impulses.
	/// Note: the contact manifold does not include time of impact impulses, which can be
	/// arbitrarily large if the sub-step is small. Hence the impulse is provided explicitly
	/// in a separate data structure.
	/// Note: this is only called for contacts that are touching, solid, and awake.
	void PostSolve(b2Contact* contact, const b2ContactImpulse* impulse)
	{
		B2_NOT_USED(contact);
		B2_NOT_USED(impulse);
		//CCLog("CCb2ContactListener::PostSolve");
	}
};

